import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 加载数据集
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)

# 打印数据集的前5行
print(df.head())

# 使用matplotlib绘制企鹅物种分布的条形图
sns.countplot(x='Species', data=df)
plt.show()

# 使用箱线图可视化不同物种的FlipperLength, CulmenLength和CulmenDepth的分布
sns.boxplot(x='Species', y='FlipperLength', data=df)
plt.show()
sns.boxplot(x='Species', y='CulmenLength', data=df)
plt.show()
sns.boxplot(x='Species', y='CulmenDepth', data=df)
plt.show()

# 显示缺失值的行
print(df.isnull().sum())

# 删除缺失值的行
df = df.dropna()

# 准备训练数据
# 1. 将数据拆分为特征和标签
# 2. 将数据拆分为训练集和测试集

# 特征是CulmenLength, CulmenDepth, FlipperLength
# 标签是Species
X = df[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
y = df['Species']

# 拆分数据集，保留30%的数据用于测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 训练逻辑回归模型
# 1. 创建一个多类逻辑回归模型
# 2. 训练模型

# 创建一个多类逻辑回归模型
model = LogisticRegression(multi_class='multinomial', solver='lbfgs')

# 训练模型
model.fit(X_train, y_train)

# 评估模型
# 1. 预测测试集的标签
# 2. 计算模型的准确性

# 预测测试集的标签
y_pred = model.predict(X_test)

# 计算模型的准确性
accuracy = accuracy_score(y_test, y_pred)
print(f'Model Accuracy: {accuracy:.2f}')